﻿using DAL;
using DianShangHouTai.Models;
using Qiniu.Common;
using Qiniu.Http;
using Qiniu.IO;
using Qiniu.IO.Model;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity.Validation;

namespace DianShangHouTai.Controllers
{
    public class ProductController : Controller
    {
        ShopContext db = new ShopContext();
        // GET: Product商品管理
        /// <summary>
        /// 单品管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {

                return View();
        }
        /// <summary>
        /// 商品搜索
        /// </summary>
        /// <returns></returns>
        public ActionResult Search()
        {
            string DanPinName = Request.Params["DanPinName"];
            int pn, pz;
            if (!int.TryParse(Request.Params["page"],out pn))
            {
                pn = 1;
            }
            if (!int.TryParse(Request.Params["Limit"],out pz))
            {
                pz = 10;
            }
            try
            {
                IQueryable<V_Productdata> res = db.V_Productdata.Where(p => true);
                if (!string.IsNullOrWhiteSpace(DanPinName))
                {
                    res = res.Where(p=>p.DanPinName.Contains(DanPinName));
                }
                var list = res.OrderByDescending(p=>p.ProductId).Skip((pn-1)*pz).Take(pz).ToList();
                return Content(Pager.PagedData<V_Productdata>(list,res.Count()));
            }
            catch (Exception ex)
            {
                return Json(new { code=1,msg="查询出错:"+ex.Message,data=new List<V_Productdata>(),count=0},JsonRequestBehavior.AllowGet);
            }
        }
     
        /// <summary>
        /// 显示商品页面数据
        /// </summary>
        /// <returns></returns>
        public ActionResult Indexdata()
        {
            using (ShopContext db = new ShopContext())
            {
                List<V_Productdata> q = db.V_Productdata.Where(p => true).ToList();
                return Content(Pager.PagedData<V_Productdata>(q, q.Count()));
            }
        }
        /// <summary>
        /// 添加商品数据
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet]
        public ActionResult AddProductData() {
            var lists = db.Product.Select(p=>new SelectListItem { Value=p.Id.ToString(),Text=p.ShopName}).ToList();
                return View(lists);
        }
        [HttpPost]
        public ActionResult AddProductData(DanPindata data)
        {
            using (ShopContext db=new ShopContext())
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        //单品表字段
                        db.DanPin.Add(new DanPin
                        {
                            DanPinName=data.DanPinName,
                            KuChun=data.KuChun,
                            Price=data.Price,
                            ProductId=data.ProductId,
                            ImgUrl = data.ImgUrl

                        });
                        var li = db.SaveChanges();
                        if (li > 0)
                        {
                            return Json(new UIResult(true, "添加成功"));
                        }
                        else
                        {
                            return Json(new UIResult(false, "添加失败"));
                        }
                    }
                    else
                    {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        int i = 1;
                        foreach (var s in ModelState.Values)
                        {
                            foreach (var p in s.Errors)
                            {
                                sb.AppendFormat("{0}-{1};", i++, p.ErrorMessage);
                            }
                        }
                        return Json(new UIResult(false, "服务器验证未通过" + sb));
                    }

                }
                catch (Exception ex)
                {

                    return Json(new UIResult(false, "出错了" + ex.Message));
                }
            }
        }
        /// <summary>
        /// 删除单行数据
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult Del(int Id)
        {
            using (ShopContext db = new ShopContext())
            {
                try
                {
                    var obj = db.DanPin.SingleOrDefault(p=>p.Id==Id);
                    if (obj!=null)
                    {
                        db.DanPin.Remove(obj);
                    }
                    int res = db.SaveChanges();
                    if (res>0)
                    {
                        return Json(new UIResult(true,"删除成功"));
                    }
                    else
                    {
                        return Json(new UIResult(false,"删除失败"));
                    }
                }
                catch (Exception ex)
                {
                    return Json(new UIResult(false,"出错了"+ex.Message));

                }

            }
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PubDel(string id)
        {
            using (ShopContext db=new ShopContext())
            {
                string sql = string.Format("delete from DanPins where [Id] in ({0})",id,DateTime.Now);
                try
                {
                    var li = db.Database.ExecuteSqlCommand(sql);
                    if (li > 0)
                    {
                        return Json(new UIResult(true, "删除成功"));
                    }
                    else {
                        return Json(new UIResult(false, "删除失败"));
                    }
                }
                catch (Exception ex)
                {
                    return Json(new UIResult(false,"删除失败"+ex.Message));
                    throw;
                }
            }
        }
        /// <summary>
        /// 商品编辑页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult EditProduct(int id)
        {
            using (ShopContext db=new ShopContext())
            {
                var li = db.DanPin.SingleOrDefault(p=>p.Id==id);
                return View(li);

            }
        }
        /// <summary>
        /// 商品编辑方法
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditProduct(V_Productdata data)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var li = db.DanPin.SingleOrDefault(p => p.Id == data.Id);
                    li.DanPinName = data.DanPinName;
                    li.Price = data.Price;
                    li.KuChun = data.KuChun;
                    li.ImgUrl = data.ImgUrl;

                    int i = db.SaveChanges();
                    if (i > 0)
                    {
                        return Json(new UIResult(true, "更新成功"));
                    }
                    else
                    {
                        return Json(new UIResult(false, "更新失败"));
                    }
                }
                else
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    int i = 1;
                    foreach (var s in ModelState.Values)
                    {
                        foreach (var p in s.Errors)
                        {
                            sb.AppendFormat("{0}-{1};", i++, p.ErrorMessage);
                        }
                    }
                    return Json(new UIResult(false, "服务端验证未通过," + sb));
                }

            }
            catch (Exception ex)
            {
                return Json(new UIResult(false, "更新失败" + ex.Message));
            }
        }
        /// <summary>
        /// 热卖管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Hotsale()
        {
            return View();
        }
        /// <summary>
        /// 留言管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Message()
        {
            return View();

        }
        public ActionResult SearchMessage(int id)
        {
            var list = RoleService.Message(id).ToList();
            return View(list);
        }
        /// <summary>
        /// 轮播图管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Banner()
        {
            return View();
        }
        public ActionResult SCTP()
        {
            return View();
        }
        [HttpPost]
        public ActionResult SCTP(UITP data)
        {
            using (ShopContext db = new ShopContext())
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        //单品表字段
                        db.Banner.Add(new Banner
                        {
                          Image=data.Image,
                          ImageNames=data.ImageNames
                        });
                        var li = db.SaveChanges();
                        if (li > 0)
                        {
                            return Json(new UIResult(true, "添加成功"));
                        }
                        else
                        {
                            return Json(new UIResult(false, "添加失败"));
                        }
                    }
                    else
                    {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        int i = 1;
                        foreach (var s in ModelState.Values)
                        {
                            foreach (var p in s.Errors)
                            {
                                sb.AppendFormat("{0}-{1};", i++, p.ErrorMessage);
                            }
                        }
                        return Json(new UIResult(false, "服务器验证未通过" + sb));
                    }

                }
                catch (Exception ex)
                {

                    return Json(new UIResult(false, "出错了" + ex.Message));
                }
            }
        }
        /// <summary>
        /// 轮播图查询
        /// </summary>
        /// <returns></returns>
        public ActionResult SearchTP()
        {
            List<Banner> ps = db.Banner.Where(p => true).ToList();
            return Content(Pager.PagedData<Banner>(ps, ps.Count()));
        }
        /// <summary>
        /// 轮播图片修改
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult BJ(int? Id)
        {
            Banner s = db.Banner.SingleOrDefault(x => x.Id == Id);
            return View(s);
        }
        [HttpPost]
        public ActionResult BJ(UITP data)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var obj = db.Banner.SingleOrDefault(p => p.Id == data.Id);
                    obj.ImageNames = data.ImageNames;
                    obj.Image = data.Image;
                    if (db.SaveChanges() > 0)
                    {
                        return Json(new UIResult(true, ""));
                    }
                    else
                    {
                        return Json(new UIResult(false, "错愕"));
                    }
                }
                else
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    int i = 1;
                    foreach (var s in ModelState.Values)
                    {
                        foreach (var p in s.Errors)
                        {
                            sb.AppendFormat("{0}-{1};", i++, p.ErrorMessage);
                        }
                    }
                    return Json(new UIResult(false, "服务端验证未通过," + sb));
                }
            }
            catch (Exception ex)
            {
                return Json(new UIResult(false, ex.Message));
            }
        }

        /// <summary>
        /// 轮播图片图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult Upalod(HttpPostedFileBase file)
        {
            //文件为空代表没有传过来
            if (file != null)
            {
                Mac mac = new Mac("N9a-Z2wNliLOejazrJ2GqmFsnsR9ZH7qXHDek41M", "AnjHBFYx96uy4aJ_w5qF0fpH3ZoqGAA6bMvQOsrI");
                string bucket = "520miss";
                //string saveKey = "myfile";
                string fileExt = file.FileName.Substring(file.FileName.LastIndexOf('.') + 1);
                //给上传的文件重新命名
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + "." + fileExt;
                byte[] data = new byte[file.ContentLength];
                //读取字节流里面的文件
                file.InputStream.Read(data, 0, data.Length);
                //byte[] data = System.Text.Encoding.UTF8.GetBytes("Hello World!");
                // 上传策略，参见 
                // https://developer.qiniu.com/kodo/manual/put-policy
                PutPolicy putPolicy = new PutPolicy();
                // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
                // putPolicy.Scope = bucket + ":" + saveKey;
                putPolicy.Scope = bucket;
                // 上传策略有效期(对应于生成的凭证的有效期)          
                putPolicy.SetExpires(3600);
                // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
                putPolicy.DeleteAfterDays = 1;
                // 生成上传凭证，参见
                // https://developer.qiniu.com/kodo/manual/upload-token            
                ZoneID zoneId = ZoneID.CN_South;
                Qiniu.Common.Config.SetZone(zoneId, false);
                string jstr = putPolicy.ToJsonString();
                string token = Auth.CreateUploadToken(mac, jstr);
                FormUploader fu = new FormUploader();
                // HttpResult result = fu.UploadData(data, saveKey, token);
                HttpResult result = fu.UploadData(data, fileName, token);
                return Json(new { status = true, message = "上传成功", remark = "http://qildjikxg.hn-bkt.clouddn.com/" + fileName }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { status = false, message = "未指定上传文件" }, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult select()
        {
            return View();
        }
    }
}
